package phone.qyg.com.qyg.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ToxicBakery.viewpager.transforms.ABaseTransformer;
import com.ToxicBakery.viewpager.transforms.AccordionTransformer;
import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.TransformController;
import com.app.view.CustomScrollView;
import com.app.view.RatingBar;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.baidu.MapActivity;
import phone.qyg.com.qyg.adapter.DiscussAdapter;
import phone.qyg.com.qyg.model.Activity;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.MapItem;
import phone.qyg.com.qyg.model.MyVenue;
import phone.qyg.com.qyg.model.MyVenueDetail;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.model.VenueActRoom;
import phone.qyg.com.qyg.model.VenueDetail;
import phone.qyg.com.qyg.model.Venues;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.DiscussUtil;
import phone.qyg.com.qyg.utils.NetworkImageHolderView;

/**
 * 作者：lblbh on 2017/11/30 09:35
 * 邮箱：lanbuhan@163.com
 * 功能：场馆详情
 */
@ContentView(R.layout.venues_detail)
public class VenuesDetailActivity extends BaseActivity {

    String ACT_COUNT = "共<font color='#ff6633'>{0}</font>个活动";
    String DISCUSS_COUNT = "共<font color='#b2b2b2'>用户评价</font>";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.title)
    TextView title;

    @ViewInject(R.id.detail_map)
    TextView detail_map;

    @ViewInject(R.id.detail_phone)
    TextView detail_phone;

    @ViewInject(R.id.detail_time)
    TextView detail_time;

    @ViewInject(R.id.more_info)
    TextView more_info;

    @ViewInject(R.id.venue_count)
    TextView venue_count;

    @ViewInject(R.id.discuss_count)
    TextView discuss_count;

    @ViewInject(R.id.discuss_more)
    TextView discuss_more;

    @ViewInject(R.id.venue_type_content)
    TextView venue_type_content;

    @ViewInject(R.id.order)
    TextView order;

    @ViewInject(R.id.rating_bar)
    RatingBar rating_bar;

    @ViewInject(R.id.scroll_view)
    CustomScrollView scroll_view;

    @ViewInject(R.id.recycler_act)
    RecyclerView  recycler_act;

    @ViewInject(R.id.type_recycler)
    RecyclerView type_recycler;

    @ViewInject(R.id.discuss_recycler)
    RecyclerView discuss_recycler;

    @ViewInject(R.id.send_discuss)
    RelativeLayout send_discuss;

    @ViewInject(R.id.act_title_layout)
    RelativeLayout act_title_layout;

    @ViewInject(R.id.venue_reserve_linear)
    LinearLayout venue_reserve_linear;

    @ViewInject(R.id.convenientBanner)
    com.app.view.ConvenientBanner convenientBanner;

    ShareAction mShareAction;

    VenueDetail model;

    VenueActRoom type;

    int id;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();
        if(obj instanceof Base){
            Base base = (Base) obj;
            id = base.id;
        }else if(obj instanceof Venues){
            Venues venues = (Venues) obj;
            id = venues.id;
        }else if(obj instanceof MapItem){
            MapItem mapItem = (MapItem) obj;
            id = mapItem.objectId;
        }else if(obj instanceof CollectionItem){
            CollectionItem collItem = (CollectionItem) obj;
            id = collItem.objectId;
        }else if (obj instanceof Roll) {
            Roll roll = (Roll) obj;
            id = roll.objectId;
        }else if (obj instanceof MyVenue) {
            MyVenue myVenue = (MyVenue) obj;
            id = myVenue.venueId;
        }else if (obj instanceof MyVenueDetail) {
            MyVenueDetail venueDetail = (MyVenueDetail) obj;
            id = venueDetail.venueId;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if(id == 0) return;
        mapKeys.put(AppHttpKey.VENUE_ID,String.valueOf(id));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.VENUE_DETAIL,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, VenueDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }else{
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });

        initDiscuss();

    }

    private void setData(){
        if(model == null)return;
        back.setText(CommonUtil.setAttributeText(model.title));
        title.setText(CommonUtil.setAttributeText(model.title));
        int star = model.star;
        rating_bar.setStar((star >=1)?(star/2):0);
        detail_map.setText(new StringBuffer(getString(R.string.map_key)).append(CommonUtil.setAttributeText(model.address)));
        detail_phone.setText("电话："+CommonUtil.setAttributeText(model.phone));
        detail_time.setText("营业时间："+CommonUtil.setAttributeText(model.offHours));
        CommonUtil.setTextViewDrawableDirection(chollect,4,
                                                    (model.isCollection == 0)?
                                                        R.drawable.title_collect_normal:
                                                        R.drawable.title_collect_select);
        //venue_count
        CommonUtil.textViewSetText(venue_count,MessageFormat.format(ACT_COUNT,model.actCount));

        //活动列表
        setVenueActs(model.actList);

        //室内活动列表
        List<VenueActRoom> types = model.venueActRoom;
        if(isRequestList(types)){
            type = types.get(0);
            type.hintType = 1;
            setVenueActRoom(types);
            venue_type_content.setText(setAttributeText(type.content));
            venue_reserve_linear.setVisibility(View.VISIBLE);
        }else{
            venue_reserve_linear.setVisibility(View.GONE);
        }

        //轮图
        setVenueRoll(model.imgList);

    }

    public void setVenueRoll(final List<Roll> models) {
        List<String> urls = new ArrayList<String>();

        for (int i=0,j=models.size();i<j;i++){
            Roll roll = models.get(i);
            urls.add(roll.fixImgUrl);
        }
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, urls)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.roll_normal, R.drawable.roll_focus})
                //设置指示器的方向
//                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
//                .setOnPageChangeListener(this)//监听翻页事件
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Roll roll = models.get(position);

                        if(roll == null)
                            return;

                        int type = roll.type;

                        if(type == 0)
                            return;

                        /**
                         “type”: 1     //轮播图类型：0-普通（无链接）1-网页链接，2-活动，3-场馆，4-专题，5-课程
                         “objectId”: 21   //对象ID（活动，场馆，专题，课程）

                         */
                        Class clazz = null;
                        if(type == 1){
                            //网页
                            clazz = HtmlActivity.class;
                        }else if(type == 2){
                            //活动
                            clazz = ActivityDetailActivity.class;
                        }else if(type == 3){
                            //场馆
                            clazz = VenuesDetailActivity.class;
                        }else if(type == 4){
                            //专题
                            clazz = CultureListActivity.class;
                        }else if(type ==5) {
                            //课程
                            clazz = CourseDetailActivity.class;
                        }

                        if(clazz != null)
                            TransformController.transformControllerModel(QXApplication.getContext(),clazz,roll);
                    }
                });
        convenientBanner.notifyDataSetChanged();

        try {
            Class cls = Class.forName("com.ToxicBakery.viewpager.transforms."+AccordionTransformer.class.getSimpleName());
            ABaseTransformer transforemer= (ABaseTransformer)cls.newInstance();
            convenientBanner.getViewPager().setPageTransformer(true,transforemer);

            //部分3D特效需要调整滑动速度
//            if(transforemerName.equals("StackTransformer")){
//                convenientBanner.setScrollDuration(1200);
//            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    //室内活动列表
    private void  setVenueActRoom(List<VenueActRoom> models){
        if(!isRequestList(models))return;

        final CommonAdapter adapter = new CommonAdapter<VenueActRoom>(QXApplication.getContext(),R.layout.item_venue_type,models) {

            @Override
            protected void convert(ViewHolder holder, final VenueActRoom model, int position) {
                holder.setText(R.id.item_title,model.title);
                holder.setVisible(R.id.one_hint,(model.hintType == 1));
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                VenueActRoom temp = (VenueActRoom) adapter.getDatas().get(position);

                if(temp == type)
                    return;

                type.hintType = 0;
                temp.hintType = 1;
                type = temp;

                venue_type_content.setText(setAttributeText(type.content));
                adapter.notifyDataSetChanged();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        type_recycler.setLayoutManager(layoutVerManager);
        type_recycler.setAdapter(adapter);
    }


    private void setVenueActs(List models){
        if(!isRequestList(models))return;

        final CommonAdapter adapter = new CommonAdapter <Activity>(QXApplication.getContext(),R.layout.venue_item_act,models) {

            @Override
            protected void convert(ViewHolder holder, final Activity model, int position) {
                holder.setText(R.id.item_title,model.title);
                holder.setText(R.id.item_address,model.startTime);
                holder.setText(R.id.item_state,model.statusName);
                holder.setText(R.id.state,model.applyBtnName);
                holder.setTextColor(R.id.item_state, model.color);
//                holder.setTextDrawStroke(R.id.item_state, model.color);
                holder.setTextColor(R.id.state, model.applyBtnColor);
                holder.setTextDrawStroke(R.id.state, model.applyBtnColor);
                holder.setVisible(R.id.state,(model.applyBtn == 1)?true:false);
                holder.setImage(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatioAct());

                holder.setOnClickListener(R.id.state, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TransformController.transformControllerModel(QXApplication.getContext(),
                                ActivityRegisActivity.class,
                                model);
                    }
                });
            }

        };

        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_act.setLayoutManager(layoutVerManager);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Object obj = adapter.getData().get(position);
                TransformController.transformControllerModel(QXApplication.getContext(),ActivityDetailActivity.class,obj);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        recycler_act.setAdapter(adapter);

    }

    private void initDiscuss(){
        AppHttpRequest.getDiscussList(id, 0, 1, new AppHttpRequest.OnAppHttpListener() {
            @Override
            public void onAppHttpState(boolean isState, String result) {
                if(isState){
                    if(JSONTool.isStatus(result)){
                        int count = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTAL_COUNT);
                        List<Object> discusses = DiscussUtil.resultChangeList(result,id);
                        setDiscussData(discusses);
//                        CommonUtil.textViewSetText(discuss_count,MessageFormat.format(DISCUSS_COUNT,count));
                    }else{
                        PromptManager.showToast(JSONTool.errorHint(result));
                    }
                }else{
                    PromptManager.showToast(R.string.service_error);
                }

            }
        });
    }

    /**
     * 设置讨论
     * @param models
     */
    private void setDiscussData(List<Object> models){
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        discuss_recycler.setLayoutManager(layoutVerManager);

        DiscussAdapter adapter = new DiscussAdapter(QXApplication.getContext(),models,ApplicationConfig.VENUE);
        discuss_recycler.setAdapter(adapter);


        back.setFocusable(true);
        back.setFocusableInTouchMode(true);
        back.requestFocus();
    }

    @Event(value = {R.id.back,R.id.share,R.id.chollect,R.id.detail_map,R.id.more_info,
                    R.id.venue_count,R.id.discuss_more,R.id.detail_phone,R.id.send_discuss,
                    R.id.order})
    private void viewOnClick(View v){
        if((null == model) && (v != back))
            return;
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(VenuesDetailActivity.this,
                        model.shareAddress,
                        model.title,
                        model.venueDesc,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.chollect:
                if(isUserLogin()){
                    final int isCollection = model.isCollection;
                    AppHttpRequest.collection(model.id, isCollection, "0", model.title, new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            if(isState ){
                                PromptManager.showToast((isCollection == 0)?R.string.conllection_sucess:R.string.conllection_quit_sucess);
                                model.isCollection = (isCollection == 0) ? 1:0;
                                CommonUtil.setTextViewDrawableDirection(chollect,4,(model.isCollection == 0)? R.drawable.title_collect_normal: R.drawable.title_collect_select);
                            }
                        }
                    });
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.detail_map:
                TransformController.transformControllerModel(QXApplication.getContext(),MapActivity.class,model);
                break;
            case R.id.more_info:
                TransformController.transformControllerModel(QXApplication.getContext(),HtmlActivity.class,model);
                break;
            case R.id.venue_count:

                break;
            case R.id.discuss_more:
                TransformController.transformControllerModel(QXApplication.getContext(),DiscussActivity.class,model);
                break;
            case R.id.detail_phone:
                final String phoneNumber = model.phone;
                if (isRequestStr(phoneNumber)) {
                    CommonUtil.showAlertDialog(this,phoneNumber,getString(R.string.sure_phone),phoneNumber);
                } else {
                    PromptManager.showToast(R.string.stop_phone);
                }
                break;
            case R.id.send_discuss:
                if(isUserLogin()){
                    TransformController.transformControllerModel(QXApplication.getContext(),ReleaseDiscussActivity.class,model);
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.order:
                if(null == type) return;
                if(isUserLogin()){
                    type.venueId = model.id;
                    type.venueTitle = model.title;
                    TransformController.transformControllerModel(QXApplication.getContext(),
                            VenueFieldActivity.class,
                            type);
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initDiscuss();
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }


    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(3000);
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    @Override
    public void initViewHandler() {}

}
